<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchConfig"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="getList"
        uniqueId="mesFqcTaskTable"
      >
      </ele-page>
    </div>
    <ele-form-drawer
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialogs"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :title="title"
      size="80%"
    >
      <template v-slot:orderCode>
        <el-input
          v-model="formDataDialog.orderCode"
          readonly
          :placeholder="$t('mesFqcTask.selectOrder')"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="mesSalesOrderDialogVisible = true"
          ></el-button>
        </el-input>
      </template>
    </ele-form-drawer>
    <ele-dialog-table
      :title="$t('mesFqcTask.productWorkOrderQuery')"
      width="800px"
      :visible.sync="mesSalesOrderDialogVisible"
      :formConfig="mesSalesOrderSearchDialog"
      :column="mesSalesOrderDialogColumn"
      @getSelectData="getSelectMesSalesOrder"
      :getList="getMesSalesOrderList"
      :hasFooter="hasMesSalesOrderFooter"
    >
    </ele-dialog-table>

    <dialogTable
      :initForm="{
        orderCode: formDataDialog.orderCode,
        capacityType: 'box_code',
      }"
      :type="5"
      ref="dialogTable"
      @responseList="responseList"
    />
  </div>
</template>

<script>
import { operateList, searchConfig, rowConfig, formDesc } from "./config";
import {
  getList,
  rowCreate,
  rowUpdate,
  rowDel,
  getInfo,
  getStatusList,
  getResultList,
} from "@/api/fqc/mesFqcTask";
import { getDict } from "@/api/common";
import { mesSalesOrderDialog } from "./mixin";
import { uniqueKey, checkStr } from "@/utils/judge";
import { getBaseCodeStrategy } from "@/api/common";
import { popover } from "@/utils/judge";
import dialogTable from "@/views/order/mesSalesOrder/components/ele-dialog-table/index.vue";
export default {
  name: "mesFqcTask",
  mixins: [mesSalesOrderDialog, formDesc],
  components: { dialogTable },
  data() {
    return {
      title: null,
      visible: false,
      isLoading: false,
      loading: false,
      formDataDialog: { codeStrategy: "" },
      //  formDescDialogs, //新增修改框
      searchConfig,
      operateList,
      getList,
      // 列表页字段的绑定配置
      column: [
        {
          type: "selection",
        },
        {
          type: "index",
          label: $i18n.t("common.order"),
          width: 60,
          fixed: "left",
        },
        {
          prop: "resultCode",
          label: $i18n.t("mesFqcTask.resultCode"),
          minWidth: 230,
          showOverflowTooltip: true,
          fixed: "left",
          render: (h, scope) => {
            return popover(scope.row.resultCode, h, "", () =>
              this.goChild({ resultCode: scope.row.resultCode })
            );

            // return (
            //   <el-button
            //     type="text"
            //     onClick={() => {
            //       this.goChild({ resultCode: scope.row.resultCode })
            //     }}>
            //     {scope.row.resultCode}
            //   </el-button>
            // )
          },
        },
        // {
        //   prop: "barcode",
        //   label: "条码号",
        //   width: 130,
        // },
        {
          prop: "planCode",
          label: $i18n.t("mesFqcTask.planCode"),
          minWidth: 200,
          showOverflowTooltip: true,
        },
        {
          prop: "orderCode",
          label: $i18n.t("mesFqcTask.productWorkOrderCode"),
          minWidth: 220,
          showOverflowTooltip: true,
        },
        {
          prop: "prodCode",
          label: $i18n.t("mesFqcTask.productCode"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "prodName",
          label: $i18n.t("mesFqcTask.productName"),
          width: 200,
          showOverflowTooltip: true,
        },
        // {
        //   prop: "templateCode",
        //   label: "模板编码",
        // },
        // {
        //   prop: "templateName",
        //   label: "模板名称",
        // },
        // {
        //   prop: "templateType",
        //   label: "模板类型--数据字典（首件、末件、巡检、抽样）",
        // },
        {
          prop: "status",
          label: $i18n.t("common.status"),
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            const list = await getStatusList();
            return list.data.result;
          },
        },
        {
          prop: "startTime",
          label: $i18n.t("mesFqcTask.startTime"),
          width: 180,
        },
        {
          prop: "endTime",
          label: $i18n.t("mesFqcTask.endTime"),
          width: 180,
        },
        {
          prop: "result",
          label: $i18n.t("mesFqcTask.checkResult"),
          optionProp: {
            value: "value",
            label: "description",
          },
          minWidth: 140,
          option: async (data) => {
            const list = await getResultList();
            return list.data.result;
          },
        },
        // {
        //   prop: "imagePath",
        //   label: "图片地址",
        // },
        // {
        //   prop: "remark",
        //   label: "备注",
        // },
        // {
        //   prop: "factoryCode",
        //   label: "工厂编码",
        // },
        {
          prop: "createByName",
          label: $i18n.t("common.createByName"),
          width: 130,
        },
        {
          prop: "createTime",
          label: $i18n.t("common.createTime"),
          width: 180,
        },
        {
          prop: "updateByName",
          label: $i18n.t("common.updateByName"),
          width: 130,
        },
        {
          prop: "updateTime",
          label: $i18n.t("common.updateTime"),
          width: 180,
        },
        {
          prop: "operate",
          label: $i18n.t("common.operation"),
          fixed: "right",
          width: 160,
          render: (h, scope) => {
            return (
              <ele-row-operation
                scope={scope}
                rowConfig={rowConfig}
                onRowOperate={this.rowOperate}
              ></ele-row-operation>
            );
          },
        },
      ],
    };
  },
  computed: {},
  methods: {
    //判断是否存在编码规则
    getBaseCodeStrategy() {
      getBaseCodeStrategy({
        code: "fqcresultcode",
        system: "default",
        strategyStatus: "1",
      }).then((res) => {
        const result = res.data.result;
        this.formDataDialog.codeStrategy =
          Array.isArray(result) && result.length > 0 ? result[0].code : "";

        this.formDescDialogs.formDesc.resultCode.required =
          !this.formDataDialog.codeStrategy;
      });
    },

    /**
     * @description  新增表格数据
     * @author bing
     * @date 2022-03-18 08:53
     */
    addList() {
      if (!this.formDataDialog.orderCode) {
        this.$message.warning($i18n.t("mesFqcTask.pleaseChoseOrder"));
        return;
      }

      this.$refs.dialogTable.visible = true;
    },
    /**
     * @descrip生产工单tion  选中表格 返回的数据
     * @author bing
     * @date 2022-03-18 10:20
     * @param {Array} data
     */
    responseList(data) {
      let list = [
        ...(this.formDataDialog?.mesFqcTaskDetailList ?? []),
        ...data.map((ite) => ite),
      ];
      // 筛选重复值,插入
      this.$set(
        this.formDataDialog,
        "mesFqcTaskDetailList",
        uniqueKey(list, "barcode")
      );
    },
    //表格顶部按钮操作事件
    handleOperateEvent({ handleName, name, rows }) {
      this.title = name;
      const fnc = {
        add: () => {
          this.changeMaster(false);
          this.formDataDialog = {
            codeStrategy: this.formDataDialog.codeStrategy,
          };
          this.visible = true;
        },
        delete: () => {
          this.$confirm(
            $i18n.t("common.deleteBatch",{name:$i18n.t('mesFqcTask.name')}),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.ok"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            const ids = rows.map((val) => val.id).join(",");
            this.rowDel(ids);
          });
        },
      };
      fnc[handleName] && fnc[handleName]();
    },
    //表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name;
      const fnc = {
        show: () => {
          // 查看详情，并打开界面
          this.editInfo(row.id, true);
        },
        edit: () => {
          if (row.status == 0) {
            this.editInfo(row.id, false);
          } else {
            this.$message.warning($i18n.t("mesFqcTask.editLimit"));
          }
          // 修改详情，并打开界面
        },
        multiAdd: () => {
          this.goMultiAdd({ id: row.id });
        },
      };
      fnc[handleName] && fnc[handleName]();
    },
    //弹框提交事件
    handleSubmit(data) {
      let list = {
        ...data,
        mesFqcTaskDetailList: (data.mesFqcTaskDetailList || []).map((ite) => {
          return { ...ite, id: "", resultCode: data.resultCode };
        }),
      };

      if (this.isLoading) return; // 判断状态
      this.isLoading = true;
      this.formDataDialog.id ? this.rowUpdate(list) : this.rowCreate(list);
    },
    //新增
    rowCreate(data) {
      rowCreate(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || $i18n.t("common.addSuccess"));
          this.visible = false;
          this.refresh();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    // 修改详情
    editInfo(id, flag) {
      this.changeMaster(flag);
      this.loading = true;
      getInfo(id)
        .then((res) => {
          this.formDataDialog = res.data.result;
          this.visible = true;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //修改
    rowUpdate(data) {
      rowUpdate(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || $i18n.t("common.editSuccess"));
          this.visible = false;
          this.refresh();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    //删除
    rowDel(data) {
      this.loading = true;
      rowDel(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || $i18n.t("common.deleteSuccess"));
          this.refresh();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset);
    },
    //跳转至子页面
    goChild(queryParam) {
      let pathParam = "/fqc/mesFqcTaskDetail";
      this.$router.push({ path: pathParam, query: queryParam });
    },
    // 跳转至批量新增页面
    goMultiAdd(queryParam) {
      let pathParam = "/fqc/mesFqcTaskAdd";
      this.$router.push({ path: pathParam, query: queryParam });
    },
    changeMaster(flag) {
      if (flag) {
        this.formDescDialogs.disabled = true;
        this.formDescDialogs.isShowSubmitBtn = false;
      } else {
        this.formDescDialogs.disabled = false;
        this.formDescDialogs.isShowSubmitBtn = true;
      }
    },
  },

  created() {
    this.getBaseCodeStrategy();
    // sendThis(this);
  },
};
</script>
